package com.oneandone.httpserver.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

/**
 * @author calin
 */
public class BasicTcpListener implements TcpListener, Runnable {
	private final static Logger LOGGER = Logger.getLogger(BasicTcpListener.class);
	
	private ServerSocket socket;
	private int port;
	private TcpConnectionHandler handler;
	public BasicTcpListener(TcpConnectionHandler handler, int port) throws IOException{
		this.handler = handler;
		this.port = port;
		socket = new ServerSocket(port);
		LOGGER.debug("Starting listener thread...");
		new Thread(this).start();
	}
    @Override
    public void run(){
        //To change body of implemented methods use File | Settings | File Templates.
		while(true){
			try {
				Socket clientSocket = socket.accept();
				LOGGER.debug("Connection Accepted:" + clientSocket);
				handler.handle(clientSocket);
			} catch (IOException e) {
				LOGGER.error("Listener exception: ", e);
			}
		}
	}

    @Override
    public void shutdown() {
        //To change body of implemented methods use File | Settings | File Templates.
    	LOGGER.debug("Listener shutting down");
    	try {
    		handler.shutdown();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
